﻿using FastCloud.Base;
using FastCloud.Base.Config;
using FastCloud.Base.DB;
using FastCloud.Base.Desgin;
using FastCloud.ORG.DB;
using FastCloud.ORG.Entity;
using FastIOC.Attribute;
using FastORM.Entity;
using FastUtil.Convert;
using FastUtil.Data;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace FastCloud.Controllers.ORG
{
    [Route("frame/org/user")]
    public class UserController : BaseController
    {
        [AutoWired]
        private DB_Config @DB_Config;
        [AutoWired]
        private DB_OU @DB_OU;
        [AutoWired]
        private DB_User @DB_User;
        [AutoWired]
        private DB_UserRole DB_UserRole;
        [AutoWired]
        private DB_UserExtend @DB_UserExtend;
        [AutoWired]
        private DB_ModuleRight DB_ModuleRight;
        [AutoWired]
        private DB_Login DB_Login;

        [Route("list")]
        public IActionResult List()
        {
            return View("~/Views/ORG/User/User_List.cshtml");
        }

        [Route("add")]
        public IActionResult Add()
        {
            return View("~/Views/ORG/User/User_Add.cshtml");
        }

        [Route("edit")]
        public IActionResult Edit()
        {
            return View("~/Views/ORG/User/User_Edit.cshtml");
        }

        [Route("modify")]
        public IActionResult Modify()
        {
            return View("~/Views/ORG/User/User_ModifyEdit.cshtml");
        }

        [Route("oplist"), HttpPost]
        public IActionResult OpList()
        {
            string UserName = ValueConvert.ConvertToString(GetFormParam("UserName"));
            string OUGuid = ValueConvert.ConvertToString(GetFormParam("OUGuid"));
            bool SearchInAll = ValueConvert.ConvertToBoolean(GetFormParam("SearchInAll"));
            string sql = "Enable=@Enable";
            List<ParamEntity> ParamList = new List<ParamEntity>() { new ParamEntity() { ParamName = "Enable", ParamValue = (int)FastCloud.Base.Enum.Common.EnableOrDisable.启用 } };
            if (!string.IsNullOrEmpty(UserName))
            {
                sql += " and UserName like @UserName";
                ParamList.Add(new ParamEntity() { ParamName = "UserName", ParamValue = "%" + UserName + "%" });
            }
            if (!SearchInAll)
            {
                if (!string.IsNullOrEmpty(OUGuid) && OUGuid != "Top")
                {
                    sql += " and OUGuid=@OUGuid";
                    ParamList.Add(new ParamEntity() { ParamName = "OUGuid", ParamValue =  OUGuid  });
                }
            }
            List<Frame_User> list = DB_User.SelectPageList("*", sql, "SortNum desc", ParamList);
            List<Frame_OU> alloulist = DB_OU.SelectAllList("OUGuid,OUName,ParentOUGuid");
            foreach (Frame_User item in list)
            {
                item.OUName = DB_OU.GetFullPathOUName(item.OUGuid, alloulist);
            }
            int count = DB_User.SelectCount(sql);
            Page page = new Page();
            page.Rows = list;
            page.Total = count;
            return Result.OK(page);
        }

        [Route("opinsert"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult OpInsert(Frame_User Entity)
        {
            Entity.Password = DB_Config.SelectConfigByName("DefaultPWD").ConfigValue;
            string UserGuid = string.IsNullOrEmpty(Entity.UserGuid) ? GenerateUtil.GenerateUnitGuid() : Entity.UserGuid;
            Entity.UserGuid = UserGuid;
            DB_User.Insert(Entity);
            Frame_UserExtend ExtendEntity = new Frame_UserExtend();
            ExtendEntity.UserGuid = UserGuid;
            ExtendEntity.Birthday = Entity.Birthday;
            ExtendEntity.QQNumber = Entity.QQNumber;
            ExtendEntity.PostalAddress = Entity.PostalAddress;
            ExtendEntity.PostalCode = Entity.PostalCode;
            ExtendEntity.IdentityCardNum = Entity.IdentityCardNum;
            ExtendEntity.CarNum = Entity.CarNum;
            DB_UserExtend.Insert(ExtendEntity);
            return Result.OK();
        }

        [Route("opupdate"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult OpUpdate(Frame_User Entity)
        {
            DB_User.UpdateByID(Entity);
            Frame_UserExtend ExtendEntity = new Frame_UserExtend();
            ExtendEntity.UserGuid = Entity.UserGuid;
            ExtendEntity.Birthday = Entity.Birthday;
            ExtendEntity.QQNumber = Entity.QQNumber;
            ExtendEntity.PostalAddress = Entity.PostalAddress;
            ExtendEntity.PostalCode = Entity.PostalCode;
            ExtendEntity.IdentityCardNum = Entity.IdentityCardNum;
            ExtendEntity.CarNum = Entity.CarNum;
            ExtendEntity.UpdateFieldList = Entity.UpdateFieldList;
            DB_UserExtend.UpdateByID(ExtendEntity);
            //同步更新frame_login
            Frame_Login LoginEntity = DB_Login.SelectOne(Entity.UserGuid);
            LoginEntity.UserName = Entity.DisplayName;
            DB_Login.UpdateByID(LoginEntity);
            return Result.OK();
        }

        [Route("opdetail"), HttpPost]
        [Transitional]
        public virtual IActionResult OpDetail()
        {
            string UserGuid = ValueConvert.ConvertToString(GetFormParam("UserGuid"));
            Frame_User Entity = DB_User.SelectOne(UserGuid);
            Frame_UserExtend ExtendEntity = DB_UserExtend.SelectOne(UserGuid);
            Entity.Birthday = ExtendEntity.Birthday;
            Entity.QQNumber = ExtendEntity.QQNumber;
            Entity.PostalAddress = ExtendEntity.PostalAddress;
            Entity.PostalCode = ExtendEntity.PostalCode;
            Entity.IdentityCardNum = ExtendEntity.IdentityCardNum;
            Entity.CarNum = ExtendEntity.CarNum;
            return Result.OK(Entity);
        }

        [Route("opbatchdelete"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult OpBatchDelete()
        {
            string KeyID = ValueConvert.ConvertToString(GetFormParam("KeyID"));
            List<string> KeyIDList = KeyID.TrimEnd(';').Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            DB_User.DeleteBatch(KeyIDList);
            //删除用户角色关系，删除模块权限
            foreach (string UserGuid in KeyIDList)
            {
                DB_UserRole.DeleteByFiled("UserGuid", UserGuid);
                DB_ModuleRight.DeleteByFiled("RightGuid", UserGuid);
            }
            return Result.OK();
        }

        [Route("opinitpwd"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult OpInitPassWord()
        {
            string UserGuid = ValueConvert.ConvertToString(GetFormParam("UserGuid"));
            DB_User.InitPWD(UserGuid);
            return Result.OK();
        }

        [Route("tree"), HttpPost]
        public IActionResult Tree()
        {
            List<Frame_OU> OUList = DB_OU.SelectAllList();
            List<Frame_User> UserList = DB_User.SelectAllList();
            OUList.Sort((x, y) => -x.SortNum.CompareTo(y.SortNum));
            UserList.Sort((x, y) => -x.SortNum.CompareTo(y.SortNum));
            List<TreeNode> NodeList = new List<TreeNode>();
            Frame_OU Root = new Frame_OU();
            Root.OUGuid = "Top";
            Root.OUName = "全部部门";
            Root.ParentOUGuid = "";
            OUList.Add(Root);
            foreach (Frame_OU item in OUList)
            {
                TreeNode node = new TreeNode();
                node.ID = item.OUGuid;
                node.Name = item.OUName;
                node.PID = item.ParentOUGuid;
                if (item.OUGuid == Root.OUGuid)
                {
                    node.IsTop = true;
                    node.Open = true;
                }
                node.InSelectResult = false;
                NodeList.Add(node);
                List<Frame_User> UserFilterList = UserList.Where(a => a.OUGuid == item.OUGuid).ToList();
                foreach (Frame_User user in UserFilterList)
                {
                    TreeNode usernode = new TreeNode();
                    usernode.ID = user.UserGuid;
                    usernode.Name = user.DisplayName;
                    usernode.PID = user.OUGuid;
                    NodeList.Add(usernode);
                }
            }
            return Result.OK(CloudUtil.BuildTree(NodeList));

        }
    }
}
